package zozopo.user;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.json.JSONException;
import org.json.JSONObject;


import zozopo.database.BusiDatabaseManager;
import zozopo.database.DatabaseManager;
import zozopo.user.operations.QQUserOS;
import zozopo.user.operations.QQUserTB;
import zozopo.user.operations.UserOS;
import zozopo.user.operations.UserTB;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class CreateUserByQQ extends  ActionSupport implements Action ,SessionAware, ServletResponseAware{
	private static final Log logger = LogFactory.getLog(LogFactory.class);

	private HttpServletResponse response;
	private Map<Object, Object> session;
	
	private String redirect;
	
	private String email;
	private String username;
	private String password;
	private String comfirmpassword;
	private String valicode;
	
	//传出参数
	private String access_token = "";
	private String expires_in = "";
	private String openid = "";
	private String userInfoJSONStr = "";
	private String client_id = "";
	
	private JSONObject userInfojson;
	
	StringBuffer setupStr1 = new  StringBuffer();
	StringBuffer setupStr2 = new  StringBuffer();
	StringBuffer setupStr3 = new  StringBuffer();
	
	//用户信息.
	private String ret = "";
	private String msg = "";
	private String nickname = "";
	private String figureurl = "";
	private String figureurl_1 = "";
	private String figureurl_2 = "";
	private String gender = "";
	
	public String execute() throws Exception {
		//ActionContext actionContext = ActionContext.getContext(); 
		DatabaseManager databaseManager = new BusiDatabaseManager();
		Connection conn = databaseManager.getConnection();
		try {  
			conn.setAutoCommit(false);
			
			UserOS userOS = new UserOS(conn);
			QQUserOS qqUserOS = new QQUserOS(conn);
			
			
			
			UserTB user = new UserTB();
			user.setQq_user("");
			user.setEmail_user("");
			user.setName_user(username);
			user.setPassword_user(password);
			
			if(!userOS.registUser(user)){
				conn.rollback();
				conn.setAutoCommit(true);
				return ERROR;
			}
			user = userOS.getUserInfoByName(username);

			
			int userid = user.getId_user();
			
			QQUserTB qquser = new QQUserTB();
			qquser.setAccess_token(access_token);
			
			qquser.setUserid(userid);
			
			
			qquser.setFigureurl(figureurl);
			qquser.setFigureurl_1(figureurl_1);
			qquser.setFigureurl_2(figureurl_2);
			qquser.setGender(gender);
			qquser.setNickname(nickname);
			qquser.setOpenid(openid);
			
			
			
			if(qqUserOS.isExistOpenId(openid)){  //如果openid已经存在就.
				conn.rollback();
				conn.setAutoCommit(true);
				return ERROR;
			}
			if(!qqUserOS.insert(qquser)){ 
				conn.rollback();
				conn.setAutoCommit(true);
				return ERROR;
			}
			
			qquser = qqUserOS.getInfo(qquser.getUserid());   //得到最新的 qqooperator INFO

			session.put("userInfo", user);
		
	        
	        conn.commit();
			conn.setAutoCommit(true);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			addFieldError("errormessage", "系统错误请联系管理人员");
			return ERROR;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			addFieldError("errormessage", "系统错误请联系管理人员");
			return ERROR;
		}finally{
			databaseManager.releaseConnection(conn);
		}
		return SUCCESS;
	}
	
	public void validate() {
		
		try {
			getQQInfo();
		} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(password.equals("")){
			addFieldError("errormessage","密码不能为空");
			return;
		}
		
		if(!password.equals(comfirmpassword)){
			addFieldError("errormessage","输入两次密码不一致请重新输入");
			return;
		}
		
		UserOS userOS = new UserOS();
		try {
			if(userOS.isExist(username)){
				//清空session valicode
				session.put("valicode", "");
				addFieldError("errormessage", getText("user.isexist"));
				userOS.releaseConnection();
				return;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		userOS.releaseConnection();
		
		
		//验证码
		ActionContext actionContext = ActionContext.getContext(); 
		String valicode = (String) actionContext.getSession().get("valicode");
		if(valicode == null || !valicode.equals(getValicode())){
			addFieldError("errormessage",getText("background.login.valicode.iswrong"));
			return;
		}
		
		
		
		
	}
	
	public String getQQInfo() throws JSONException, IOException{
		
		access_token = (String) session.get("access_token");
		openid = (String) session.get("openid");
		
		//第三步.
		String setup2 ="https://graph.qq.com/user/get_user_info?access_token="+access_token+"&oauth_consumer_key=100231532&openid="+openid;  
		//{ "ret":0, "msg":"", "nickname":"啊编先生", "figureurl":"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/30", "figureurl_1":"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/50", "figureurl_2":"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/100", "gender":"男" } 
		
		URL url3= new URL(setup2);
		HttpURLConnection urlconn3 = (HttpURLConnection) url3.openConnection();
		urlconn3.connect();
		InputStream stream = urlconn3.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(stream,"UTF-8"));
		
		
		String temp3 ="";
		while((temp3 = reader.readLine()) != null){
			setupStr3.append(temp3+"\n");
		}
		
		urlconn3.disconnect();
		stream.close();
		reader.close();
		
		userInfojson= new JSONObject(setupStr3.toString());
		
		ret = userInfojson.get("ret").toString();
		msg = userInfojson.get("msg").toString();
		nickname = userInfojson.get("nickname").toString();
		figureurl = userInfojson.get("figureurl").toString();
		figureurl_1 = userInfojson.get("figureurl_1").toString();
		figureurl_2 = userInfojson.get("figureurl_2").toString();
		gender = userInfojson.get("gender").toString();

	
		return "";
	}
	
	public String getQQInfoTest() throws JSONException{
		
		//access_token=91C1291E02D224240AC21725348F53A0&expires_in=7776000
	
		setupStr1.append("access_token=91C1291E02D224240AC21725348F53A0&expires_in=7776000");
		
		String[] strArry = setupStr1.toString().split("&");
		String[] strArry2 = strArry[0].split("=");
		access_token = strArry2[1];
		//setupStr1.append(" URL:" +url + " access_token:" + access_token);
		
		//第二步.
		setupStr2.append("callback( {\"client_id\":\"100231532\",\"openid\":\"BBCE43A56DC0F1AF2FB407518A4F1240\"} );");
		String setupStr = setupStr2.toString();
		setupStr =  setupStr.substring(setupStr.indexOf("(")+1);
		setupStr = setupStr.substring(0, setupStr.indexOf(")"));
		
		JSONObject jsonStr = new JSONObject(setupStr);
		
		client_id = jsonStr.get("client_id").toString();
		openid = jsonStr.get("openid").toString();
		//第三步.
		//{ "ret":0, "msg":"", "nickname":"啊编先生", "figureurl":"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/30", "figureurl_1":"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/50", "figureurl_2":"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/100", "gender":"男" } 

		setupStr3.append("{ \"ret\":0, \"msg\":\"\", \"nickname\":\"啊编先生\", \"figureurl\":\"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/30\", \"figureurl_1\":" +
				"\"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/50\"," +
				" \"figureurl_2\":\"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/100\", \"gender\":\"男\" } ");
	
		
		userInfojson= new JSONObject(setupStr3.toString());
		
		ret = userInfojson.get("ret").toString();
		msg = userInfojson.get("msg").toString();
		nickname = userInfojson.get("nickname").toString();
		figureurl = userInfojson.get("figureurl").toString();
		figureurl_1 = userInfojson.get("figureurl_1").toString();
		figureurl_2 = userInfojson.get("figureurl_2").toString();
		gender = userInfojson.get("gender").toString();
		
		userInfoJSONStr = userInfojson.toString();
		//*/

	
	return "";
}

	
	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	

	public String getValicode() {
		return valicode;
	}

	public void setValicode(String valicode) {
		this.valicode = valicode;
	}

	public void setSession(Map arg0) {
		// TODO Auto-generated method stub
		session = arg0;
	}
	public void setServletResponse(HttpServletResponse arg0) {
		// TODO Auto-generated method stub
		response = arg0;
	}
	
	public String getRedirect() {
		return redirect;
	}

	public void setRedirect(String redirect) {
		
		this.redirect = redirect;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getComfirmpassword() {
		return comfirmpassword;
	}

	public void setComfirmpassword(String comfirmpassword) {
		this.comfirmpassword = comfirmpassword;
	}

	public String getAccess_token() {
		return access_token;
	}

	public void setAccess_token(String access_token) {
		this.access_token = access_token;
	}

	public String getExpires_in() {
		return expires_in;
	}

	public void setExpires_in(String expires_in) {
		this.expires_in = expires_in;
	}

	public String getOpenid() {
		return openid;
	}

	public void setOpenid(String openid) {
		this.openid = openid;
	}

	public String getClient_id() {
		return client_id;
	}

	public void setClient_id(String client_id) {
		this.client_id = client_id;
	}

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public String getFigureurl() {
		return figureurl;
	}

	public void setFigureurl(String figureurl) {
		this.figureurl = figureurl;
	}

	public String getFigureurl_1() {
		return figureurl_1;
	}

	public void setFigureurl_1(String figureurl_1) {
		this.figureurl_1 = figureurl_1;
	}

	public String getFigureurl_2() {
		return figureurl_2;
	}

	public void setFigureurl_2(String figureurl_2) {
		this.figureurl_2 = figureurl_2;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}


}
